package draw

import (
	"encoding/json"
	"errors"
	"math/rand"
	"strconv"
	"strings"
	"sync"
	"time"
	"vrcm/src/vrcm/app/admin/models"
	"vrcm/src/vrcm/app/admin/models/draw"
	"vrcm/src/vrcm/app/admin/models/live"
	dto "vrcm/src/vrcm/app/admin/service/dto/draw"
	"vrcm/src/vrcm/common/apis"
	cDto "vrcm/src/vrcm/common/dto"
	"vrcm/src/vrcm/common/service"
)

type DrawService struct {
	service.Service
}

var m sync.Mutex

func (e *DrawService) GetPage(c *dto.DrawBasicGetPageReq, list *[]draw.DrawBasic, count *int64) error {
	var err error
	var data draw.DrawBasic
	db := e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		)
	if len(c.BindId) > 0 {
		db.Where("bind_id = ?", c.BindId)
	}
	if c.Round > 0 {
		db.Where("round = ?", c.Round)
	}
	err = db.
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("DrawService GetPage error:%s \r\n", err)
		return err
	}

	ids := make([]int, 0, 5)
	for _, v := range *list {
		v := v
		ids = append(ids, v.Id)
	}

	//页面设置
	claimPrizes := make([]draw.ClaimPrize, 0, 5)
	err = e.Orm.Model(&draw.ClaimPrize{}).Where("draw_id in ?", ids).Find(&claimPrizes).Error
	if err != nil {
		e.Log.Errorf("get PrizeConfig error:%s \r\n", err)
		return err
	}

	//奖品数统计
	prizeResults := make([]draw.PrizeResult, 0, 5)
	err = e.Orm.Model(&draw.PrizeConfig{}).Select("draw_id, SUM(prize_num) as prize_num").Where("draw_id in ?", ids).Group("draw_id").Find(&prizeResults).Error
	if err != nil {
		e.Log.Errorf("get PrizeConfig error:%s \r\n", err)
		return err
	}

	//中奖人数统计
	records := make([]draw.Record, 0, 5)
	err = e.Orm.Model(&draw.AwardRecord{}).Select("draw_id, count(*) as record_num").Where("draw_id in ?", ids).Group("draw_id").Find(&records).Error
	if err != nil {
		e.Log.Errorf("get AwardRecord error:%s \r\n", err)
		return err
	}

	for k, v := range *list {
		v := v
		for _, prize := range prizeResults {
			if prize.DrawID == v.Id {
				(*list)[k].AwardNum = prize.PrizeNum
			}
		}
		for _, record := range records {
			if record.DrawID == v.Id {
				(*list)[k].AwardUserNum = record.RecordNum
			}
		}
		for _, claimPrize := range claimPrizes {
			claimPrize := claimPrize
			if claimPrize.DrawId == v.Id {
				(*list)[k].ClaimPrize = claimPrize
			}
		}
	}
	return nil
}

func (e *DrawService) SaveDrawBasic(c *dto.DrawSaveReq) error {

	if c.IsSwitch == 1 && c.Id > 0 {
		err := e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.Id).Update("join_type", c.JoinType).Error
		if err != nil {
			e.Log.Errorf("update DrawBasic error:", err)
			return err
		}
		return nil
	}

	var err error
	var data draw.DrawBasic
	if c.Id > 0 {
		err = e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.Id).Find(&data).Error
		if err != nil {
			e.Log.Errorf("get DrawBasic error:", err)
			return err
		}
	}
	now := time.Now().Unix()
	data.Id = c.Id
	data.TenantId = c.TenantId
	data.Animation = c.Animation
	data.BindId = c.BindId
	data.DrawTitle = c.DrawTitle
	data.IsRepeat = c.IsRepeat
	data.Round = c.Round
	if c.Id > 0 {
		data.UpdateTime = now
	} else {
		data.DrawState = 2
		data.UpdateTime = now
		data.CreateTime = now
	}
	data.JoinType = c.JoinType
	err = e.Orm.Save(&data).Error
	if err != nil {
		e.Log.Errorf("创建抽奖失败:%s \r\n", err)
		return err
	}

	if c.Id <= 0 {
		claimPrize := draw.ClaimPrize{}
		claimPrize.DrawId = data.Id
		claimPrize.TenantId = c.TenantId
		claimPrize.PrizeType = 1
		err = e.Orm.Save(&claimPrize).Error
		if err != nil {
			e.Log.Errorf("创建抽奖页面设置失败:%s \r\n", err)
			return err
		}
	}
	c.Id = data.Id
	return nil
}

func (e *DrawService) GetDrawBasic(c *dto.GetDrawReq) (error, draw.DrawBasic) {
	var err error
	var data draw.DrawBasic
	err = e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.Id).Find(&data).Error
	if err != nil {
		e.Log.Errorf("get DrawBasic error:", err)
		return err, data
	}
	var claimDraw draw.ClaimPrize
	err = e.Orm.Model(&draw.ClaimPrize{}).Where("draw_id=?", c.Id).Find(&claimDraw).Error
	if err != nil {
		e.Log.Errorf("get ClaimPrize error:", err)
		return err, data
	}
	data.ClaimPrize = claimDraw
	prizes := make([]draw.PrizeConfig, 0, 5)
	err = e.Orm.Model(&draw.PrizeConfig{}).Where("draw_id=?", c.Id).Find(&prizes).Error
	if err != nil {
		e.Log.Errorf("get PrizeConfig error:", err)
		return err, data
	}
	data.PrizeConfigs = prizes
	drawWhites := make([]draw.DrawWhite, 0, 5)
	err = e.Orm.Model(&draw.DrawWhite{}).Where("draw_id=?", c.Id).Find(&drawWhites).Error
	if err != nil {
		e.Log.Errorf("get DrawWhite error:", err)
		return err, data
	}
	data.DrawWhites = drawWhites
	return nil, data
}

func (e *DrawService) GetDrawingBasic(c *dto.GetDrawingReq) (error, draw.DrawBasic) {
	var err error
	var data draw.DrawBasic
	err = e.Orm.Model(&draw.DrawBasic{}).Where("bind_id=? and round=? and draw_state=1", c.BindId, c.Round).Find(&data).Error
	if err != nil {
		e.Log.Errorf("get DrawBasic error:", err)
		return err, data
	}
	var claimDraw draw.ClaimPrize
	err = e.Orm.Model(&draw.ClaimPrize{}).Where("draw_id=?", data.Id).Find(&claimDraw).Error
	if err != nil {
		e.Log.Errorf("get ClaimPrize error:", err)
		return err, data
	}
	data.ClaimPrize = claimDraw
	prizes := make([]draw.PrizeConfig, 0, 5)
	err = e.Orm.Model(&draw.PrizeConfig{}).Where("draw_id=?", data.Id).Find(&prizes).Error
	if err != nil {
		e.Log.Errorf("get PrizeConfig error:", err)
		return err, data
	}
	data.PrizeConfigs = prizes
	return nil, data
}

func (e *DrawService) StartDraw(c *dto.StartDrawReq) error {
	param := make(map[string]interface{})
	if c.SceneType == 1 {
		var data draw.DrawBasic
		err := e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.Id).Find(&data).Error
		if err != nil {
			e.Log.Errorf("get DrawBasic:%s \r\n", err)
			return err
		}

		info := draw.DrawInfo{}
		info.DrawId = data.Id
		info.DrawState = 1
		s, _ := json.Marshal(&info)
		bindId, _ := strconv.Atoi(data.BindId)
		err = e.Orm.Model(&live.LiveBasic{}).Where("id=?", bindId).Update("draw_id", s).Error
		if err != nil {
			e.Log.Errorf("update LiveBasic:%s \r\n", err)
			return err
		}

		var liveBasic live.LiveBasic
		err = e.Orm.Model(&live.LiveBasic{}).Where("id=?", data.BindId).Find(&liveBasic).Error
		if err != nil {
			e.Log.Errorf("get LiveBasic:%s \r\n", err)
			return err
		}

		////重新复制场次
		//param["round"] = liveBasic.RoundId
		drawKey := models.DrawPrefix + models.Delimiter + data.TenantId + models.Delimiter + data.BindId

		err = e.Redis.Set(drawKey, string(s), -1)
		if err != nil {
			e.Log.Errorf("set drawKey error:%s \r\n", err)
			return err
		}
	}

	param["draw_state"] = 1
	param["update_time"] = time.Now().Unix()
	err := e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.Id).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("update DrawBasic:%s \r\n", err)
		return err
	}

	return nil
}

func (e *DrawService) EndDraw(c *dto.EndDrawReq) error {
	param := make(map[string]interface{})
	param["draw_state"] = 3
	param["update_time"] = time.Now().Unix()
	err := e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.Id).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("update DrawBasic:%s \r\n", err)
		return err
	}

	//获取中奖配置
	drawWhites := make([]draw.DrawWhite, 0, 5)
	err = e.Orm.Model(&draw.DrawWhite{}).Where("draw_id=?", c.Id).Find(&drawWhites).Error
	if err != nil {
		e.Log.Errorf("get DrawWhite:%s \r\n", err)
		return err
	}

	joinType := 0
	if len(drawWhites) > 0 {
		joinType = drawWhites[0].JoinType
	}

	var data draw.DrawBasic
	err = e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.Id).Find(&data).Error
	if err != nil {
		e.Log.Errorf("get DrawBasic:%s \r\n", err)
		return err
	}

	//获取参与用户
	drawWhiteMap := make(map[int][]draw.DrawWhite)
	users := make([]draw.DrawUser, 0, 5)
	if joinType == 2 {
		for _, v := range drawWhites {
			v := v
			user := draw.DrawUser{}
			user.DrawId = v.DrawId
			user.TenantId = v.TenantId
			user.Round = data.Round
			user.MobilePhone = v.PhoneOrEmail
			user.UserName = v.PhoneOrEmail
			users = append(users, user)
			drawsWhites, ok := drawWhiteMap[v.PrizeId]
			if !ok {
				drawsWhites = make([]draw.DrawWhite, 0, 5)
			}
			drawsWhites = append(drawsWhites, v)
			drawWhiteMap[v.PrizeId] = drawsWhites
		}
	} else {
		err = e.Orm.Model(&draw.DrawUser{}).Where("draw_id=?", c.Id).Find(&users).Error
		if err != nil {
			e.Log.Errorf("get DrawUser:%s \r\n", err)
			return err
		}
	}

	//获取奖品项目
	prizes := make([]draw.PrizeConfig, 0, 5)
	err = e.Orm.Model(&draw.PrizeConfig{}).Where("draw_id=?", c.Id).Find(&prizes).Error
	if err != nil {
		e.Log.Errorf("get PrizeConfig:%s \r\n", err)
		return err
	}

	now := time.Now().Unix()
	awardRecords := make([]draw.AwardRecord, 0, 5)
	var m sync.Mutex
	m.Lock()
	// 设置随机数种子
	rand.Seed(time.Now().UnixNano())
	if len(users) > 0 {
		for _, v := range prizes {
			v := v
			prizeNum := v.PrizeNum
			if joinType == 2 {
				drawWhites := drawWhiteMap[v.Id]
				//白名单消耗必中奖项
				for _, white := range drawWhites {
					if len(users) == 0 {
						break
					}
					for index, user := range users {
						if strings.Contains(user.MobilePhone, white.PhoneOrEmail) && white.IsSelect == 1 {
							users = append(users[:index], users[index+1:]...)
						}
					}
					awardRecord := draw.AwardRecord{}
					awardRecord.DrawId = v.DrawId
					awardRecord.TenantId = v.TenantId
					awardRecord.PrizeId = v.Id
					awardRecord.AwardUserId = 0
					awardRecord.DrawTitle = data.DrawTitle
					awardRecord.PrizeName = v.PrizeName
					awardRecord.UserName = white.PhoneOrEmail
					awardRecord.Address = white.PhoneOrEmail
					awardRecord.MobilePhone = white.PhoneOrEmail
					awardRecord.WriteState = 2
					awardRecord.CreateTime = now
					awardRecord.UpdateTime = now
					awardRecords = append(awardRecords, awardRecord)
				}
				prizeNum = prizeNum - len(drawWhites)
			}

			//白名单必中参与抽奖或者全员参与抽奖
			for i := 0; i < prizeNum; i++ {
				awardRecord := draw.AwardRecord{}
				if len(users) == 0 {
					break
				}

				index := rand.Intn(len(users))
				winner := users[index]

				//白名单或者不允许重复抽奖 踢出已经中奖用户
				if data.IsRepeat != 1 || joinType == 2 {
					users = append(users[:index], users[index+1:]...)
				}

				awardRecord.DrawId = v.DrawId
				awardRecord.TenantId = v.TenantId
				awardRecord.PrizeId = v.Id
				awardRecord.AwardUserId = winner.Id
				awardRecord.DrawTitle = data.DrawTitle
				awardRecord.PrizeName = v.PrizeName
				awardRecord.UserName = winner.UserName
				awardRecord.Address = winner.Address
				awardRecord.MobilePhone = winner.MobilePhone
				awardRecord.WriteState = 2
				awardRecord.CreateTime = now
				awardRecord.UpdateTime = now
				awardRecords = append(awardRecords, awardRecord)
			}
		}
	}
	if len(awardRecords) > 0 {
		err = e.Orm.Model(&draw.AwardRecord{}).Create(&awardRecords).Error
		if err != nil {
			e.Log.Errorf("save awardRecords error:%s \r\n", err)
			return err
		}
	}

	if c.SceneType == 1 {
		info := draw.DrawInfo{}
		info.DrawId = data.Id
		info.DrawState = 2
		s, _ := json.Marshal(&info)
		bindId, _ := strconv.Atoi(data.BindId)
		err = e.Orm.Model(&live.LiveBasic{}).Where("id=?", bindId).Update("draw_id", s).Error
		if err != nil {
			e.Log.Errorf("update LiveBasic:%s \r\n", err)
			return err
		}
		drawKey := models.DrawPrefix + models.Delimiter + data.TenantId + models.Delimiter + data.BindId
		err = e.Redis.Set(drawKey, string(s), -1)
		if err != nil {
			e.Log.Errorf("set drawKey error:%s \r\n", err)
			return err
		}
	}

	m.Unlock()

	return nil
}

func (e *DrawService) CopyDrawBasic(c *dto.DrawCopyReq) error {

	basic := &draw.DrawBasic{}
	err := e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.Id).Find(&basic).Error
	if err != nil {
		e.Log.Errorf("get DrawBasic:%s ", err)
		return err
	}

	basic.Id = 0
	basic.DrawState = 2
	err = e.Orm.Model(&draw.DrawBasic{}).Create(&basic).Error
	if err != nil {
		e.Log.Errorf("create DrawBasic:%s ", err)
		return err
	}

	prizes := make([]draw.PrizeConfig, 0, 3)
	err = e.Orm.Model(&draw.PrizeConfig{}).Where("draw_id=?", c.Id).Find(&prizes).Error
	if err != nil {
		e.Log.Errorf("get PrizeConfig:%s ", err)
		return err
	}
	addPrizes := make([]draw.PrizeConfig, 0, 3)
	for _, prize := range prizes {
		prize := prize
		prize.Id = 0
		prize.DrawId = basic.Id
		addPrizes = append(addPrizes, prize)
	}
	if len(addPrizes) > 0 {
		err = e.Orm.Model(&draw.PrizeConfig{}).Create(&addPrizes).Error
		if err != nil {
			e.Log.Errorf("create PrizeConfig:%s ", err)
			return err
		}
	}

	prize := &draw.ClaimPrize{}
	err = e.Orm.Model(&draw.ClaimPrize{}).Where("draw_id=?", c.Id).Find(&prize).Error
	if err != nil {
		e.Log.Errorf("get ClaimPrize:%s ", err)
		return err
	}
	prize.Id = 0
	prize.DrawId = basic.Id
	err = e.Orm.Model(&draw.ClaimPrize{}).Create(&prize).Error
	if err != nil {
		e.Log.Errorf("create ClaimPrize:%s ", err)
		return err
	}
	c.Id = basic.Id
	return nil
}

func (e *DrawService) DeleteDrawBasic(c *dto.DrawDeleteReq) error {
	err := e.Orm.Model(&draw.PrizeConfig{}).Where("draw_id=?", c.Id).Delete(&draw.PrizeConfig{}).Error
	if err != nil {
		e.Log.Errorf("Delete PrizeConfig:%s ", err)
		return err
	}
	err = e.Orm.Model(&draw.ClaimPrize{}).Where("draw_id=?", c.Id).Delete(&draw.ClaimPrize{}).Error
	if err != nil {
		e.Log.Errorf("Delete ClaimPrize:%s ", err)
		return err
	}
	err = e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.Id).Delete(&draw.DrawBasic{}).Error
	if err != nil {
		e.Log.Errorf("Delete DrawBasic:%s ", err)
		return err
	}

	err = e.Orm.Model(&draw.DrawUser{}).Where("draw_id=?", c.Id).Delete(&draw.DrawUser{}).Error
	if err != nil {
		e.Log.Errorf("Delete DrawUser:%s ", err)
		return err
	}

	err = e.Orm.Model(&draw.AwardRecord{}).Where("draw_id=?", c.Id).Delete(&draw.AwardRecord{}).Error
	if err != nil {
		e.Log.Errorf("Delete AwardRecord:%s ", err)
		return err
	}
	return nil
}

func (e *DrawService) SaveClaimPrize(c *dto.ClaimPrizeSaveReq) error {
	var err error
	var data draw.ClaimPrize
	if c.Id > 0 {
		err = e.Orm.Model(&draw.ClaimPrize{}).Where("id=?", c.Id).Find(&data).Error
		if err != nil {
			e.Log.Errorf("get ClaimPrize error:", err)
			return err
		}
	}
	now := time.Now().Unix()
	data.Id = c.Id
	data.TenantId = c.TenantId
	data.DrawId = c.DrawId
	data.PrizeType = c.PrizeType
	if c.Id > 0 {
		data.UpdateTime = now
	} else {
		data.CreateTime = now
		data.UpdateTime = now
	}
	err = e.Orm.Save(&data).Error
	if err != nil {
		e.Log.Errorf("保存发送奖品失败:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	return nil
}

func (e *DrawService) SavePrizeConfig(c *dto.PrizeConfigSaveReq) error {
	var err error
	var data draw.PrizeConfig
	if c.Id > 0 {
		err = e.Orm.Model(&draw.PrizeConfig{}).Where("id=?", c.Id).Find(&data).Error
		if err != nil {
			e.Log.Errorf("get PrizeConfig error:", err)
			return err
		}
	}
	now := time.Now().Unix()
	data.Id = c.Id
	data.TenantId = c.TenantId
	data.DrawId = c.DrawId
	data.PrizeName = c.PrizeName
	data.PrizeImg = c.PrizeImg
	data.PrizeNum = c.PrizeNum
	if c.Id > 0 {
		data.UpdateTime = now
	} else {
		data.CreateTime = now
		data.UpdateTime = now
	}
	data.UpdateTime = now
	err = e.Orm.Save(&data).Error
	if err != nil {
		e.Log.Errorf("保存奖品配置失败:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	return nil
}

func (e *DrawService) CopyPrizeConfig(c *dto.PrizeConfigCopyReq) error {
	p := &draw.PrizeConfig{}
	err := e.Orm.Model(&draw.PrizeConfig{}).Where("id=?", c.Id).Find(&p).Error
	if err != nil {
		e.Log.Errorf("get PrizeConfig:%s ", err)
		return err
	}

	p.Id = 0
	err = e.Orm.Model(&draw.PrizeConfig{}).Where("id=?", c.Id).Create(&p).Error
	if err != nil {
		e.Log.Errorf("create PrizeConfig:%s ", err)
		return err
	}
	c.Id = p.Id
	return nil
}

func (e *DrawService) DeletePrizeConfig(c *dto.PrizeConfigDeleteReq) error {
	err := e.Orm.Model(&draw.PrizeConfig{}).Where("id=?", c.Id).Delete(&draw.PrizeConfig{}).Error
	if err != nil {
		e.Log.Errorf("Delete PrizeConfig error:%s ", err)
		return err
	}
	return nil
}

func (e *DrawService) ClickDraw(c *dto.ClickDrawReq) error {

	m.Lock()
	defer m.Unlock()
	var drawBasic draw.DrawBasic
	err := e.Orm.Model(&draw.DrawBasic{}).Where("id=? ", c.DrawId).Find(&drawBasic).Error
	if err != nil {
		e.Log.Errorf("get drawBasic err:%s ", err)
		return err
	}

	//不在抽奖中直接返回
	if drawBasic.DrawState != 1 {
		return nil
	}

	var drawUser draw.DrawUser
	err = e.Orm.Model(&draw.DrawUser{}).Where("draw_id=? and user_name=? ", c.DrawId, c.UserName).Find(&drawUser).Error
	if err != nil {
		e.Log.Errorf("get DrawUser err:%s ", err)
		return err
	}
	if drawUser.Id > 0 {
		return errors.New(string(apis.RepeatDrawError.Code))
	}
	drawUser.TenantId = c.TenantId
	drawUser.DrawId = c.DrawId
	drawUser.Round = c.Round
	drawUser.UserName = c.UserName
	drawUser.MobilePhone = c.MobilePhone
	drawUser.Address = c.Address
	now := time.Now().Unix()
	drawUser.CreateTime = now
	drawUser.UpdateTime = now
	err = e.Orm.Model(&draw.DrawUser{}).Create(&drawUser).Error
	if err != nil {
		e.Log.Errorf("create drawUser error:%s ", err)
		return err
	}
	return nil
}

func (e *DrawService) SaveAwardInfo(c *dto.SaveAwardInfoReq) error {
	var err error
	var record draw.AwardRecord
	err = e.Orm.Model(&draw.AwardRecord{}).Where("id=?", c.AwardRecordId).Find(&record).Error
	if err != nil {
		e.Log.Errorf("SaveAwardInfo error:", err)
		return err
	}
	record.UserName = c.UserName
	record.MobilePhone = c.MobilePhone
	record.Address = c.Address
	record.WriteState = 1
	err = e.Orm.Model(&draw.AwardRecord{}).Where("id=?", c.AwardRecordId).Save(&record).Error
	if err != nil {
		e.Log.Errorf("save AwardRecord error:", err)
		return err
	}
	return nil
}

func (e *DrawService) GetAwardInfo(c *dto.GetAwardInfoReq) (error, []draw.AwardRecord) {
	var err error
	records := make([]draw.AwardRecord, 0, 5)
	err = e.Orm.Model(&draw.AwardRecord{}).Where("draw_id=?", c.DrawId).Find(&records).Error
	if err != nil {
		e.Log.Errorf("get AwardRecord error:", err)
		return err, records
	}
	return nil, records
}

func (e *DrawService) GetUserAwardInfo(c *dto.GetUserAwardInfoReq) (error, []draw.UserAwardInfo) {
	var err error
	basics := make([]draw.DrawBasic, 0, 5)
	infos := make([]draw.UserAwardInfo, 0, 5)
	err = e.Orm.Model(&draw.DrawBasic{}).Where("bind_id=? and round=?", c.BindId, c.Round).Find(&basics).Error
	if err != nil {
		e.Log.Errorf("get DrawBasic error:", err)
	}
	ids := make([]int, 0, 5)
	for _, basic := range basics {
		ids = append(ids, basic.Id)
	}
	records := make([]draw.AwardRecord, 0, 5)
	err = e.Orm.Model(&draw.AwardRecord{}).Where("draw_id in ? and user_name =?", ids, c.UserName).Find(&records).Error
	if err != nil {
		e.Log.Errorf("get AwardRecord error:", err)
		return err, infos
	}
	awardRecordMap := make(map[int]draw.AwardRecord)
	for _, record := range records {
		record := record
		awardRecordMap[record.DrawId] = record
	}

	for _, v := range basics {
		v := v
		info := draw.UserAwardInfo{}
		info.DrawId = v.Id
		info.DrawTitle = v.DrawTitle
		if v.DrawState == 1 {
			info.AwardState = "抽奖中"
			infos = append(infos, info)
			continue
		}
		awardRecord, ok := awardRecordMap[v.Id]
		if ok {
			info.AwardState = "中奖"
		} else {
			info.AwardState = "未中奖"
		}
		info.WriteState = awardRecord.WriteState
		infos = append(infos, info)
	}
	return nil, infos
}

func (e *DrawService) AddDrawWhites(c *dto.AddDrawWhiteReq) error {
	var err error

	if len(c.DrawWhites) <= 0 {
		return nil
	}
	err = e.Orm.Model(&draw.DrawWhite{}).Where("draw_id=?", c.DrawWhites[0].DrawId).Delete(&draw.DrawWhite{}).Error
	if err != nil {
		e.Log.Errorf("get DrawWhite error:", err)
		return err
	}

	//获取奖项配置
	prizes := make([]draw.PrizeConfig, 0, 5)
	err = e.Orm.Model(&draw.PrizeConfig{}).Where("draw_id=?", c.DrawWhites[0].DrawId).Find(&prizes).Error
	if err != nil {
		e.Log.Errorf("get PrizeConfig error:", err)
		return err
	}
	prizeNum := 0
	prizeMap := make(map[int]int)
	for _, prize := range prizes {
		prizeMap[prize.Id] = prize.PrizeNum
		prizeNum = prizeNum + prize.PrizeNum
	}

	if prizeNum > len(c.DrawWhites) {
		return errors.New(string(apis.DrawWhiteNumError.Code))
	}

	drawWhites := make([]draw.DrawWhite, 0, 5)
	whitePrizeMap := make(map[int]int)
	for _, white := range c.DrawWhites {
		drawWhite := draw.DrawWhite{}
		drawWhite.TenantId = c.TenantId
		drawWhite.PrizeId = white.PrizeId
		drawWhite.IsSelect = white.IsSelect
		drawWhite.JoinType = c.JoinType
		drawWhite.DrawId = c.DrawId
		drawWhite.PhoneOrEmail = white.PhoneOrEmail
		drawWhites = append(drawWhites, drawWhite)
		if drawWhite.IsSelect == 1 {
			num := whitePrizeMap[drawWhite.PrizeId]
			num = num + 1
			whitePrizeMap[drawWhite.PrizeId] = num
		}
	}

	for k, num := range prizeMap {
		whiteNum := whitePrizeMap[k]
		if num < whiteNum {
			return errors.New(string(apis.DrawWhiteNumError.Code))
		}
	}
	err = e.Orm.Model(&draw.DrawWhite{}).Create(&drawWhites).Error
	if err != nil {
		e.Log.Errorf("save DrawWhites error:", err)
		return err
	}

	err = e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.DrawId).Update("join_type", c.JoinType).Error
	if err != nil {
		e.Log.Errorf("save DrawBasic error:", err)
		return err
	}
	return nil

}

func (e *DrawService) SaveDrawWhite(c *dto.SaveDrawWhiteReq) error {
	var err error

	drawWhite := draw.DrawWhite{}
	drawWhite.Id = c.Id
	drawWhite.TenantId = c.TenantId
	drawWhite.PrizeId = c.PrizeId
	drawWhite.IsSelect = c.IsSelect
	drawWhite.JoinType = c.JoinType
	drawWhite.DrawId = c.DrawId
	drawWhite.PhoneOrEmail = c.PhoneOrEmail
	err = e.Orm.Save(&drawWhite).Error
	if err != nil {
		e.Log.Errorf("save DrawWhite error:", err)
		return err
	}
	err = e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.DrawId).Update("join_type", c.JoinType).Error
	if err != nil {
		e.Log.Errorf("save DrawBasic error:", err)
		return err
	}
	c.Id = drawWhite.Id
	return nil

}

func (e *DrawService) DeleteDrawWhite(c *dto.DeleteDrawWhiteReq) error {
	var err error
	err = e.Orm.Model(&draw.DrawWhite{}).Where("id in ?", c.Ids).Delete(&draw.DrawWhite{}).Error
	if err != nil {
		e.Log.Errorf("delete DrawWhite error:", err)
		return err
	}
	return nil

}

func (e *DrawService) GetDrawWhite(c *dto.GetDrawWhiteReq) (draw.DrawWhite, error) {
	var err error
	drawWhite := draw.DrawWhite{}
	err = e.Orm.Model(&draw.DrawWhite{}).Where("id = ?", c.Id).Find(&drawWhite).Error
	if err != nil {
		e.Log.Errorf("get DrawWhite error:", err)
		return drawWhite, err
	}
	return drawWhite, nil

}

func (e *DrawService) SavePrizePage(c *dto.SavePrizePageReq) error {
	var err error
	var basic draw.DrawBasic
	err = e.Orm.Model(&draw.DrawBasic{}).Where("id=?", c.DrawId).Find(&basic).Error
	if err != nil {
		e.Log.Errorf("get DrawBasic error:", err)
		return err
	}
	basic.SecretNum = c.SecretNum
	basic.QRCode = c.QRCode
	basic.Tip = c.Tip
	err = e.Orm.Save(&basic).Error
	if err != nil {
		e.Log.Errorf("save DrawBasic error:", err)
		return err
	}
	return nil
}
